<template>
  <div class="login">
    <!-- 文件上传组件使用 -->

    <Form @submit="onSubmit" class="fom">
      <div class="person">
        <Uploader
          :after-read="afterRead"
          v-model="fileList"
          :max-count="1"
          class="image-header"
        />
      </div>

      <cell-group inset>
        <field
          v-model="userName"
          name="userName"
          label="用户名"
          placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <field
          v-model="pswd"
          type="password"
          name="pswd"
          label="确认密码"
          placeholder="请再次输入密码"
          :rules="[{ required: true, message: '请再次输入密码' }]"
        />
      </cell-group>
      <div class="login-router-link">
        <p>有账户,<router-link :to="{ name: 'login' }">注册</router-link></p>
      </div>
      <div style="margin: 16px">
        <Button round block type="primary" native-type="submit">提交</Button>
      </div>
    </Form>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { Form, Field, CellGroup, Button, Uploader, Toast } from "vant";
import { uploadFileAPI, enterAPI } from "../../services/auth";
import { setToken } from "../../uitils/Token";
import { urlImg } from "../../uitils/urlImg";
const { push } = useRouter();
const userName = ref("");
const password = ref("");
const pswd = ref("");
const fileList = ref([]);
const uploadImg = ref("");
// 注册[判断]
const onSubmit = (values) => {
  // console.log("submit", values);
  if (pswd.value === password.value) {
    enterAPI({
      userName: values.userName,
      password: values.password,
      avatar: uploadImg.value,
    }).then((res) => {
      // console.log(res.data);
      //@ts-ignore
      if (res.code === 1) {
        // console.log(111);

        Toast.success("注册成功");
        setToken(res.data);
        setTimeout(() => {
          push("/user");
        }, 2000);
      } else {
        Toast.fail(res.data);
      }
    });
  } else {
    Toast.fail("两次密码不一样");
  }
};

// 下面是 上传头像的问题
const afterRead = (file) => {
  // FormData是js内置对象
  const formData = new FormData();
  formData.append("file", file.file);
  // 此时可以自行将文件上传至服务器
  // console.log(file);
  uploadFileAPI(formData).then((res) => {
    console.log(res.data);
    // fileList.value.push({
    //   url: urlImg(res.data),
    // });
    uploadImg.value = urlImg(res.data);
  });
};
</script>
<style scoped lang="scss">
.login {
  width: 100vw;
  height: 100vh;
  .fom {
    max-width: 100%;
    .person {
      text-align: center;
      margin: auto;
      .image-header {
        display: block;
        margin: 5rem auto;
        margin-left: 38vw;
      }
    }
  }
}
</style>
